package com.berchen.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.berchen.common.KeyEnum;
import com.berchen.utils.Log4jUtils;
import com.berchen.utils.RedisUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * 用户验证是否登录的一个拦截器
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {
    private static Logger logger=Logger.getLogger(LoginInterceptor.class);
    @Autowired
    private RedisUtils redisUtils;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String method = request.getMethod();
        // 跳过预检请求  （请求方式OPTIONS）
        if("OPTIONS".equals(method)){
            return true;
        }
        // 设置响应头
        String token = request.getHeader("token");
        try {
            PrintWriter writer = null;
            if (StringUtils.isEmpty(token)) {
                response.setContentType("text/html; charset=utf-8");// 这个必须要写在获取writer之前 否则中文字符会有问题
                writer=response.getWriter();
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("msg", "缺少认证信息，请添加token。");
                jsonObject.put("code", 1);
                writer.print(jsonObject.toJSONString());
                return false;
            }
            if (!redisUtils.exists(KeyEnum.USER_TOKEN.getKey() + token)) {
                response.setContentType("text/html; charset=utf-8");
                writer=response.getWriter();
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("msg", "您还未登录，请先登录。");
                jsonObject.put("code", 1);
                writer.print(jsonObject.toJSONString());
                return false;
            }
            return true;
        }catch (Exception e){

            logger.error(Log4jUtils.getTrace(e));
            return false;
        }
    }
}
